#!/bin/bash

TEMPLATE_IP="10.0.0.10"
#TARGET_IP="10.0.0.23"
HOSTNAME_PRE="ubuntu22-0-"
NETWORK_CONF="/etc/netplan/eth0.yaml"

while true;do
    read -rp "please enter a ipaddress or exit: " TARGET_IP
    if [ "$TARGET_IP" = "exit" ];then
        exit
    else
        if [[ $TARGET_IP =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]];then
            TARGET_HOSTNAME="${HOSTNAME_PRE}${TARGET_IP##*.}"
            # shellcheck disable=SC2029
            ssh  root@${TEMPLATE_IP}  "sed -i  's/${TEMPLATE_IP}/${TARGET_IP}/g' $NETWORK_CONF; \
                                            hostnamectl set-hostname $TARGET_HOSTNAME; \
                                            nohup netplan apply &> /dev/null & exit"
        else
            echo "请输入正确的IP地址，或输入exit退出此脚本"
        fi
    fi
done